package com.enation.app.javashop.consumer.shop.distribution;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dag.eagleshop.core.account.utils.HttpUtils;
import com.dag.eagleshop.core.delivery.model.dto.JsonBean;
import com.enation.app.javashop.consumer.core.event.MemberRegisterEvent;
import com.enation.app.javashop.core.base.message.MemberRegisterMsg;
import com.enation.app.javashop.core.client.distribution.CommissionTplClient;
import com.enation.app.javashop.core.client.distribution.DistributionClient;
import com.enation.app.javashop.core.distribution.model.dos.CommissionTpl;
import com.enation.app.javashop.core.distribution.model.dos.DistributionDO;
import com.enation.app.javashop.core.distribution.model.enums.DistributionConstants;
import com.enation.app.javashop.core.distribution.model.vo.DistributionRelationshipVO;
import com.enation.app.javashop.core.distribution.service.DistributionManager;
import com.enation.app.javashop.core.distribution.service.ShortUrlManager;
import com.enation.app.javashop.core.member.model.dos.Member;
import com.enation.app.javashop.core.member.service.MemberInviterManager;
import com.enation.app.javashop.core.member.service.MemberManager;
import com.enation.app.javashop.core.promotion.coupon.service.CouponManager;
import com.enation.app.javashop.core.system.enums.WechatMiniproTemplateTypeEnum;
import com.enation.app.javashop.core.system.sendMessage.WechatSendMessage;
import com.enation.app.javashop.core.system.service.WechatPublicManager;
import com.enation.app.javashop.framework.cache.Cache;
import com.enation.app.javashop.framework.util.DateUtil;
import com.enation.app.javashop.framework.util.DictUtils;
import com.enation.app.javashop.framework.util.StringUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 注册后添加分销商
 *
 * @author Chopper
 * @version v1.0
 * @Description:
 * @since v7.0
 * 2018/6/13 下午11:33
 */
@Component
public class DistributionRegisterConsumer implements MemberRegisterEvent{
    @Autowired
    private DistributionClient distributionClient;
    @Autowired
    private DistributionManager distributionManager;
    @Autowired
    private CommissionTplClient commissionTplClient;

    protected final Log logger = LogFactory.getLog(this.getClass());
    @Autowired
    private Cache cache;
    @Autowired
    private CouponManager couponManager;
    @Autowired
    private MemberManager memberManager;
    @Autowired
    private WechatPublicManager wechatPublicManager;

    @Value("${service.webSocket.url}")
    private String url;

    /** 使用webSocket推消息 */
    private static final String WEB_SOCKET = "/websocket/websocket_push_message";


    @Transactional(value = "distributionTransactionManager",rollbackFor=Exception.class)
    @Override
    public void memberRegister(MemberRegisterMsg memberRegisterMsg) {
        // 注册完毕后 在分销商表中添加会员信息
        DistributionDO distributor = new DistributionDO();
        Member member = memberRegisterMsg.getMember();
        Integer memberId = member.getMemberId();
        try {
            distributor.setMemberId(memberId);
            //默认模版设置
            CommissionTpl commissionTpl= commissionTplClient.getDefaultCommission();
            if(commissionTpl == null){
                commissionTpl = new CommissionTpl();
                commissionTpl.setId(0);
                commissionTpl.setTplName("空模板");
            }
            distributor.setCurrentTplId(commissionTpl.getId());
            distributor.setCurrentTplName(commissionTpl.getTplName());
            distributor.setMemberName(member.getUname());
            distributor.setDistributorGrade(1);
            distributor.setDistributorTitle("运营经理");
            distributor.setStatus(1);
            // 随机一个邀请码
            distributor.setInviteCode(distributionManager.randomInviteCode());
            distributor = this.distributionClient.add(distributor);
            distributor.setPath("0|" + distributor.getMemberId() + "|");
            this.distributionClient.edit(distributor);
        } catch (RuntimeException e) {
            logger.error(e);
        }

        //注册完毕后，给注册会员添加他的上级分销商id
        Object upMemberId = cache.get(ShortUrlManager.PREFIX + memberRegisterMsg.getUuid());
        logger.debug("Distribution_cache_upMemberId:" + upMemberId + "," + memberRegisterMsg.getUuid());
        try {
            //如果推广的会员id存在
            if (upMemberId != null) {
                Object visitChannel = cache.get(MemberInviterManager.CHANNEL + memberRegisterMsg.getUuid());

                int lv1MemberId = Integer.parseInt(upMemberId.toString());
                DistributionDO parentDistributor = this.distributionClient.getDistributorByMemberId(lv1MemberId);
                distributor.setPath(parentDistributor.getPath() + distributor.getMemberId() + "|");
                distributor.setLv1CreateTime(DateUtil.getDateline());
                distributor.setLv1ExpireTime(DateUtil.getDateline() + DistributionConstants.EXPIRE_TIME); // 过期时间30天 单位秒
                if(visitChannel != null){
                    try{
                        distributor.setVisitChannel(Integer.parseInt(String.valueOf(visitChannel)));
                    }catch (Exception e){
                        e.printStackTrace();
                        distributor.setVisitChannel(-1);
                    }finally {
                        cache.remove(MemberInviterManager.CHANNEL + memberRegisterMsg.getUuid());
                    }
                }

                //先更新 path
                this.distributionClient.edit(distributor);
                // 再更新parentId
                this.distributionClient.setParentDistributorId(memberId, lv1MemberId);

                // 通过推广领券 注册的 不发店铺新人券
                if(distributor.getVisitChannel() == null || distributor.getVisitChannel() != 6){
                    // 给用户 新人卷  0 标识
                    couponManager.memberRegister(memberRegisterMsg,0,member.getCity());
                }

                // 记录绑定日志
                DistributionRelationshipVO nowDistributionRelationshipVO = distributionManager.buildDistributionRelationshipVO(memberId,
                        lv1MemberId, "团长绑定",3,  "点击分享链接绑定");
                List<DistributionRelationshipVO> distributionRelationshipVOList = new ArrayList<>();
                distributionRelationshipVOList.add(nowDistributionRelationshipVO);
                distributionManager.addDistributionRelationshipVO(distributionRelationshipVOList);


                try {
                    // 查询当前人进入的渠道 从推广领券 给他发拉新券
                    if(distributor.getVisitChannel() != null && distributor.getVisitChannel() == 6){

                        // 页面数据
                        String recommendedCouponsVal = DictUtils.getDictValue("", "推荐领券", "RECOMMENDED_COUPONS");
                        if(StringUtil.isEmpty(recommendedCouponsVal)){
                            return;
                        }
                        JSONObject json = JSON.parseObject(recommendedCouponsVal);
                        String startTime = json.getString("startTime");
                        String endTime = json.getString("endTime");
                        if(StringUtil.isEmpty(startTime)){
                            return;
                        }else {
                            // 活动开始时间大于当前时间  活动还没有开始
                            long startTimeTimeLong = DateUtil.getDateline(startTime, "yyyy-MM-dd HH:mm:ss");
                            if(startTimeTimeLong > DateUtil.getDateline()){
                                return;
                            }
                        }

                        if(StringUtil.notEmpty(endTime)){
                            // 活动结束时间 小于当前时间 活动已经结束
                            long endTimeLong = DateUtil.getDateline(endTime, "yyyy-MM-dd HH:mm:ss");
                            if(endTimeLong < DateUtil.getDateline()){
                                return;
                            }
                        }
                        // 邀请人奖励
                        JSONArray typeValye = json.getJSONArray("typeValye");
                        Integer myFriendsRegisterReward = 0;
                        if(!CollectionUtils.isEmpty(typeValye)){
                            JSONObject jsonObject = JSON.parseObject(typeValye.getString(0));
                            myFriendsRegisterReward = jsonObject.getInteger("myFriendsRegisterReward");
                        }
                        // 被绑定的人会员对象
                        Member upMember = memberManager.getModel(Integer.valueOf(upMemberId.toString()));

                        // 发券
                        // 给邀请人发券
                        JSONArray myCouponIds = json.getJSONArray("myCouponIds");
                        if(!CollectionUtils.isEmpty(myCouponIds)){
                            List<Integer> myCouponIdList = myCouponIds.toJavaList(Integer.class);
                            for (Integer myCouponId : myCouponIdList) {
                                couponManager.issueVouchersToUsers(upMember,myCouponId);
                            }
                        }
                        // 给被邀请人发券
                        JSONArray friendsCouponIds = json.getJSONArray("friendsCouponIds");
                        if(!CollectionUtils.isEmpty(friendsCouponIds)){
                            List<Integer> friendsCouponIdList = friendsCouponIds.toJavaList(Integer.class);
                            for (Integer friendsCouponId : friendsCouponIdList) {
                                couponManager.issueVouchersToUsers(member,friendsCouponId);
                            }
                        }
                        // 组合webSocket消息
                        Map<String,Object> map = new HashMap<>();
                        map.put("type",2);
                        map.put("nick_name",upMember.getNickname());
                        map.put("reward",myFriendsRegisterReward);
                        // 推送webSocket
                        WechatSendMessage.WX_MESSAGE_EXECUTOR.execute(() -> {
                            String requestPath = url + WEB_SOCKET;
                            HttpUtils.httpPostByJson(requestPath, JSON.toJSON(map).toString(), JsonBean.class);
                        });
                        // 向公众号推送被邀请人注册状况
                        wechatPublicManager.sendRecommendedCouponsMessageFromPublic(member, WechatMiniproTemplateTypeEnum.PUBLIC_RECOMMENDED_COUPONS_NOTICE,
                                myFriendsRegisterReward);
                    }
                }catch (Exception e){
                    logger.error("邀请注册的人发优惠券:"+e);
                }

            } else {
                // 给用户 新人卷  0 标识
                couponManager.memberRegister(memberRegisterMsg,0,member.getCity());

                this.distributionClient.edit(distributor);
            }
            cache.remove(ShortUrlManager.PREFIX + memberRegisterMsg.getUuid());
        } catch (Exception e) {
            logger.error(e);
        }
    }


}
